/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.starlink.common.scheduled;

import com.starlink.model.domain.SchoolbagOrderDO;
import com.starlink.service.SchoolbagOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author zhanghong
 * @version SchoolbagOrderTask.java, v 0.1 2024/6/21 00:14 下午 SchoolbagOrderTask Exp $$
 */
@Slf4j
@Service
public class SchoolbagOrderTask {

    @Autowired
    private SchoolbagOrderService schoolbagOrderService;

    /**
     * 订单支付超时取消
     */
    @Scheduled(cron = "0 */1 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void unPayOrderCancel() {
        schoolbagOrderService.lambdaUpdate().eq(SchoolbagOrderDO::getOrderStatus, 1).lt(SchoolbagOrderDO::getTimeout, new Date()).remove();
    }

    /**
     * 未成功分组订单
     */
    @Scheduled(cron = "0 */1 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void joinGroupOrder() {
        List<SchoolbagOrderDO> unJoinGroupOrders = schoolbagOrderService.lambdaQuery()
                .eq(SchoolbagOrderDO::getOrderStatus, 2)
                .isNull(SchoolbagOrderDO::getSchoolbagGroupId)
                .list();
        if (CollectionUtils.isEmpty(unJoinGroupOrders)) {
            return;
        }

        for (SchoolbagOrderDO unJoinGroupOrder : unJoinGroupOrders) {
            try {
                schoolbagOrderService.joinGroup(unJoinGroupOrder.getId());
            } catch (Exception e) {
                log.error("joinGroupOrder - 定时任务一步编组失败，需要人工介入处理 orderId={}; errorMessage={}", unJoinGroupOrder.getId(), e.getMessage(), e);
            }
        }
    }
}
